import React, { useState, useRef, useMemo } from 'react'
import { useMouse, useThrottle } from 'ahooks'

import SvgIcon from '../../common/svg-icon'
import { outOfArea } from '../../../util/index'
import './split-options.scss'
import videoStore from '@/store/video.js'

const SplitOptions = () => {
  const [visible, setVisible] = useState(false)
  const [optId, setOptId] = useState('')

  const btnRef = useRef()
  const optRef = useRef()

  const mouse = useMouse()
  const throttledValue = useThrottle(mouse, { wait: 500 })

  useMemo(() => {
    if (visible) {
      if (outOfArea(optRef.current, throttledValue) && outOfArea(btnRef.current, throttledValue)) {
        setVisible(false)
      }
    }
  }, [throttledValue])

  function Options() {
    const icons = [
      {
        name: '#iconscreen-16',
        mode: 16,
      },
      {
        name: '#iconscreen-9',
        mode: 9,
      },
      {
        name: '#iconscreen-9',
        mode: 7,
      },
      {
        name: '#iconscreen-9',
        mode: 6,
      },
      {
        name: '#iconscreen-9',
        mode: 5,
      },
      {
        name: '#iconscreen-4',
        mode: 4,
      },
      {
        name: '#iconscreen-1',
        mode: 1,
      },
    ]

    function onMouseDown(mode) {
      videoStore.setLastMode(videoStore.mode)
      videoStore.setMode(mode)
      setVisible(false)
    }

    return icons.map(({ mode, name }, index) => {
      return (
        <div
          className="split-opt"
          key={index}
          onMouseDown={() => onMouseDown(mode)}
          onMouseOver={() => setOptId(index)}
          style={{ background: index === optId ? '#646464' : '#222222' }}
        >
          <SvgIcon icon={name} marginRight="10" />
          <span>{mode}分屏</span>
        </div>
      )
    })
  }

  return (
    <div
      style={{ position: 'relative', cursor: 'pointer' }}
      onMouseEnter={() => setVisible(true)}
      onClick={() => setVisible(true)}
    >
      {/* 分屏选项 */}
      <div ref={optRef} style={{ display: visible ? 'block' : 'none' }} className="panel">
        <div className="item">
          <Options />
        </div>
      </div>
      {/* 分屏按钮 */}
      <div ref={btnRef}>
        <SvgIcon icon="#iconsplit-screen" />
      </div>
    </div>
  )
}

export default SplitOptions
